class Solution {
    vector<string> ret;
    string path;
    int left, right;    //左右括号的总个数
    int curLeft, curRight;  //已经用了的左右括号的个数

    void dfs()
    {
        if (path.size() == left + right)
        {
            ret.push_back(path);
            return;
        }

        if (curLeft < left)
        {
            curLeft++;
            path += "(";
            dfs();
            path.pop_back();
            curLeft--;
        }
        if (curRight < curLeft)
        {
            curRight++;
            path += ")";
            dfs();
            path.pop_back();
            curRight--;
        }
    }
public:
    vector<string> generateParenthesis(int n) {
        left = right = n;
        curLeft = curRight = 0;
        dfs();
        return ret;
    }
};